<template>
  <m-window-frame
    title="项目合并"
    class="v-project-merge"
    ok-text="开始合并"
    show-win-max
    :ok-loading="okLoading"
    close-in-project-switch
    @ok="handleMerge"
    @cancel="handleCancel"
  >
    <el-tabs
      v-model="activeTabKey"
      type="card"
      class="g-panel-tabs"
      :closable="false"
      @tab-remove="tabRemove"
      @tab-change="tabChange"
    >
      <el-tab-pane
        v-for="item in tabList"
        :key="item.key"
        :label="$t(item.label)"
        :closable="item.closable"
        :name="item.key"
      >
        <template #label>
          <m-tab-item
            :label="$t(item.label)"
            style="justify-content: center; display: inline-block"
          />
        </template>
        <component
          :is="item.component"
          :data="item.data"
          :type="item.key.split('_')[1]"
          @open-diagram="openDiagram"
          @open-model-merge="openModelMerge"
        ></component>
      </el-tab-pane>
    </el-tabs>
  </m-window-frame>
</template>

<script lang="ts"></script>
<script lang="ts" setup>
import { ref, shallowReactive, provide } from "vue";
import { MergeModelData, Status } from "./component/logic";
import type { Shape } from "@/mdesign-lib/mdesign-graph.umd.js";
import { loading } from "@/common/Loading";
import { ProjectMergeTab } from "./types";
import MWindowFrame from "@/common/ipcWindow/WindowFrame.vue";
import MTabItem from "@/modules/model/comps/common/TabItem.vue";
import ModelMerge from "./ModelMerge.vue";
import DiagramMerge from "./DiagramMerge.vue";
import { ipcWindowUtil } from "@/common/ipcWindow/IpcWindowUtil";
import { WindowName } from "@/mdesign-lib/mdesign-main.js";
import { projectService } from "../../service";
import { CloseData, MergeParam } from "./index";
import type { TabPanelName } from "element-plus";

const { sourceProjectId, targetProjectId, rootId, sourceProjectName, targetProjectName, isSourceOnline, isSourceOpened } = app.$route
  .query as unknown as MergeParam;

provide("sourceProjectId", sourceProjectId);
provide("targetProjectId", targetProjectId);
provide("rootId", rootId);
provide("isSourceOnline", isSourceOnline);

const tabList = shallowReactive<Array<ProjectMergeTab>>([
  {
    key: "mainTab", // 模型合并窗口使用这个key，如果是画布窗口使用instanceId做为key
    label: "模型合并",
    closable: false,
    component: ModelMerge
  }
]);

const okLoading = ref(false);
let activeTabKey = ref(tabList[0].key);
// 打开图tab
function openDiagram(modelId: string, data: MergeModelData) {
  if (!modelId) return;
  let labels = [data.name];
  let keys = [data.id];
  if (data.status === Status.ADD) {
    labels[0] = `${data.name}【（源）${sourceProjectName}】`;
    keys[0] = `${data.id}_source`;
  } else if (data.status === Status.DELETED || data.status === Status.UNMODIFIED) {
    labels[0] = `${data.name}【（目标）${targetProjectName}】`;
    keys[0] = `${data.id}_target`;
  } else {
    // 有变动的要打开两张图
    labels[0] = `${data.name}【（源）${sourceProjectName}】`;
    keys[0] = `${data.id}_source`;
    labels[1] = `${data.name}【（目标）${targetProjectName}】`;
    keys[1] = `${data.id}_target`;
  }
  activeTabKey.value = keys[0];
  if (keys.length > 1) {
    activeTabKey.value = keys[1];
  }

  const tab = tabList.find(it => it.key === keys[0]);
  if (!tab) {
    tabList.push({
      key: keys[0],
      label: labels[0],
      closable: true,
      data,
      component: DiagramMerge
    });
  }
  if (keys.length === 2) {
    const tab = tabList.find(it => it.key === keys[1]);
    if (!tab) {
      tabList.push({
        key: keys[1],
        label: labels[1],
        closable: true,
        data,
        component: DiagramMerge
      });
    }
  }
}

async function openModelMerge(shape: Shape) {
  activeTabKey.value = "mainTab";
}

function tabChange(targetName: TabPanelName) {
  activeTabKey.value = targetName.toString();
}
function tabRemove(targetName: TabPanelName) {
  activeTabKey.value = "mainTab";
  const index = tabList.findIndex(i => i.key == targetName.toString());
  if (index > 0) {
    tabList.splice(index, 1);
  }
}

function handleMerge() {
  loading.popup("正在合并中，请稍等...");
  let closeSourceProject = true;
  if (isSourceOpened) {
    closeSourceProject = false;
  }
  projectService
    .projectMergeFinish(targetProjectId, sourceProjectId, closeSourceProject)
    .then(
      res => {
        ipcWindowUtil.closeWindow({ windowName: WindowName.ProjectMerge, success: true });
      },
      err => {
        if (err) {
          ipcWindowUtil.closeWindow({
            windowName: WindowName.ProjectMerge,
            success: false,
            errorMessage: err.message,
            errorTitle: err.title,
            errorLevel: err.errorLevel
          } as CloseData);
        }
      }
    )
    .finally(() => {
      loading.close();
    });
}

async function handleCancel() {
  const ok = await app.$confirm.popup({
    title: "提示",
    subTitle: "确定要取消合并操作？",
    content: "如果您取消合并操作，所有已编辑变更将会被舍弃。",
    status: "warn"
  });
  if (ok.type == "cancel") return;
  ipcWindowUtil.closeWindow({ windowName: WindowName.ProjectMerge, success: false } as CloseData);
}
</script>

<style lang="scss" scoped>
:deep(.g-panel-tabs.el-tabs.el-tabs--card .el-tabs__header.is-top .el-tabs__item:not(:first-child) .tab-title span) {
  padding-right: 10px;
}
:deep(.el-tabs--card > .el-tabs__header .el-tabs__item .is-icon-close) {
  right: 13px;
}
</style>
